<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="案例昵称" prop="demoTitle">
        <el-input
          v-model="queryParams.demoTitle"
          placeholder="请输入案例昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['projects:SlDemos:add']"
        >新增案例</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['projects:SlDemos:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="SlDemosList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="案例昵称" align="center" prop="demoTitle" />
      <el-table-column label="案例描述" align="center" prop="demoText" />
      <el-table-column label="案例操作次数" align="center" prop="demoTimes" />
      <el-table-column label="案例效果百分比" align="center" prop="demoRadios" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['projects:SlDemos:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['projects:SlDemos:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改案例对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 第一行：案例昵称和案例描述 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="案例昵称" prop="demoTitle">
              <el-input v-model="form.demoTitle" placeholder="请输入案例昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="案例描述" prop="demoText">
              <el-input v-model="form.demoText" placeholder="请输入案例描述" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 第二行：案例操作次数和案例效果百分比 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="操作次数" prop="demoTimes">
              <el-input v-model.number="form.demoTimes" placeholder="请输入案例操作次数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="脱毛效果" prop="demoRadios">
              <el-input v-model.number="form.demoRadios" placeholder="请输入案例效果百分比" type="number" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 最后：案例轮播图上传 -->
        <el-form-item label="案例轮播图" prop="swiperImgs">
          <el-upload 
            ref="upload" 
            :file-list="fileList" 
            :action="uploadUrl" 
            :headers="headers"
            :auto-upload="true" 
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :on-error="handleUploadError"
            list-type="picture-card"
            accept="image/jpeg,image/png,image/jpg"
            :limit="5"
            name="file">
            <i v-if="!uploadLoading" class="el-icon-plus"></i>
            <el-loading v-else type="spinner" size="small"></el-loading>
            <div slot="tip" class="el-upload__tip">
              支持上传 JPG/PNG 格式图片，单张不超过 2MB，最多上传 5 张
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSlDemos, getSlDemos, delSlDemos, addSlDemos, updateSlDemos } from "@/api/projects/SlDemos";
import { getToken } from "@/utils/auth";

export default {
  name: "SlDemos",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 案例表格数据
      SlDemosList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        demoTitle: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        demoTitle: [
          { required: true, message: "请输入案例昵称", trigger: "blur" }
        ],
        demoTimes: [
          { required: true, type: "number", message: "请输入案例操作次数", trigger: "blur" }
        ],
        demoRadios: [
          { required: true, type: "number", message: "请输入案例效果百分比", trigger: "blur" }
        ]
      },
      // 图片上传相关
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      headers: {
        Authorization: "Bearer " + getToken()
      },
      fileList: [],
      uploadLoading: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询案例列表 */
    getList() {
      this.loading = true;
      listSlDemos(this.queryParams).then(response => {
        this.SlDemosList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        swiperImgs: "",
        demoTitle: null,
        demoText: null,
        demoTimes: null,
        demoRadios: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null
      };
      this.fileList = [];
      this.uploadLoading = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加案例";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSlDemos(id).then(response => {
        this.form = response.data;
        // 处理图片回显
        if (this.form.swiperImgs) {
          const imgUrls = this.form.swiperImgs.split(',');
          this.fileList = imgUrls.map(url => ({
            name: `image-${Date.now()}`,
            url: url
          }));
        }
        this.open = true;
        this.title = "修改案例";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理图片数据，转为逗号分隔的字符串
          this.form.swiperImgs = this.fileList.map(file => file.url).join(',');
          
          if (this.form.id != null) {
            updateSlDemos(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSlDemos(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除案例编号为"' + ids + '"的数据项？').then(function() {
        return delSlDemos(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('projects/SlDemos/export', {
        ...this.queryParams
      }, `SlDemos_${new Date().getTime()}.xlsx`)
    },
    /** 图片上传前校验 */
    beforeUpload(file) {
      // 显示上传中状态
      this.uploadLoading = true;
      
      // 校验文件大小
      const isLt2MB = file.size / 1024 / 1024 <= 2;
      if (!isLt2MB) {
        this.$message.error('上传图片大小不能超过 2MB!');
        this.uploadLoading = false;
        return false;
      }
      
      // 校验文件格式
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
      if (!isImage) {
        this.$message.error('请上传 JPG/PNG 格式的图片!');
        this.uploadLoading = false;
        return false;
      }
      
      return true;
    },
    /** 图片上传成功处理 */
    handleUploadSuccess(response, file, fileList) {
      this.uploadLoading = false;
      if (response.code === 200) {
        // 替换为服务器返回的URL
        file.url = response.url;
        this.fileList = fileList;
        this.$message.success('图片上传成功');
      } else {
        this.handleUploadError(response, file);
      }
    },
    /** 图片上传失败处理 */
    handleUploadError(response, file) {
      this.uploadLoading = false;
      this.$message.error(response.msg || '图片上传失败，请重试');
      // 从文件列表中移除失败的文件
      this.fileList = this.fileList.filter(f => f.uid !== file.uid);
    },
    /** 移除图片处理 */
    handleRemove(file, fileList) {
      this.fileList = fileList;
      // 更新表单中的图片数据
      this.form.swiperImgs = fileList.map(f => f.url).join(',');
    }
  }
};
</script>
